<?php
declare(strict_types=1);
/**
 * Created by PhpStorm
 * User: Administrator
 * Date: 2023/11/16
 * Time: 14:02:33
 */

namespace App\Amqp\Consumer;

use \Hyperf\Amqp\Message\ConsumerMessage;
use Hyperf\Amqp\Annotation\Consumer;
use Hyperf\Amqp\Message\Type;
use Hyperf\Amqp\Result;
use PhpAmqpLib\Message\AMQPMessage;
use Service\Consumer\YunCangConsumer\Router\goodsChange;
use Service\Code\Normal;
use Service\MonitorService\MonitorService;

/**
 * BBC商品分组队列消费功能
 * @Consumer(exchange="BBC_GOODS_GROUP", routingKey="BBC_GOODS_GROUP", queue="BBC_GOODS_GROUP", nums=1) 
 */
class GoodsGroupConsumer extends ConsumerMessage
{
    protected $type = Type::DIRECT;//直连模式
    protected $qos  = [
        'prefetch_count'    => 10
    ];

    public function consumeMessage($data, AMQPMessage $message) :string{
        try {
            $result = goodsChange::instance()->goodsGroup($data);
            if( $result['code'] == Normal::SUC ) {
                return Result::ACK;
            }

            $contents = json_encode($result,JSON_UNESCAPED_UNICODE);
            MonitorService::instance()->sendMsg($contents,'BBC_GOODS_GROUP队列消费异常');
            sleep(3);//休眠3秒之后，重回队列
            return Result::REQUEUE;
        } catch ( \Throwable $t ) {

            $error = [
                'error'         => $t->getMessage(),
                'errorFile'     => $t->getFile(),
                'errorLine'     => $t->getLine(),
            ];
            $contents = json_encode($error,JSON_UNESCAPED_UNICODE);
            MonitorService::instance()->sendMsg($contents,'BBC_GOODS_GROUP队列消费异常');
            sleep(3);//休眠3秒之后，重回队列
            return Result::REQUEUE;
        }
    }
    
    /**
     * 设置是否自启动
     */
    public function isEnable() : bool
    {
        $isDisAable = env('AMQP_BBC_GOODS_GROUP_CONSUMER_DISABLE');
        return $isDisAable ? false : true ;
    }
}